package com.ychs.lawyer.service.impl;

import cn.hutool.json.JSONUtil;
import com.ychs.lawyer.bean.ResultCode;
import com.ychs.lawyer.bean.User;
import com.ychs.lawyer.exception.BussinessException;
import com.ychs.lawyer.mapper.LawyerMapper;
import com.ychs.lawyer.mapper.MenuMapper;
import com.ychs.lawyer.mapper.UserMapper;
import com.ychs.lawyer.service.UserSevice;
import com.ychs.lawyer.util.JwtUtils;
import com.ychs.lawyer.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: clh
 * @Date: 2024/07/25/16:13
 * @Description:
 */
@Service
@Slf4j
public class UserServiceImpl implements UserSevice {
      @Autowired
      private UserMapper userMapper;
      @Autowired
      private BCryptPasswordEncoder passwordEncoder;
      @Autowired
      private LawyerMapper lawyerMapper;
      @Autowired
      private StringRedisTemplate stringRedisTemplate;
      @Autowired
    private MenuMapper menuMapper;


    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> login(User user) {
          //获取其当前用户
        User user1 = userMapper.loadUserByUsername(user);
        if(user1 == null) {
//            throw new RuntimeException("用户不存在");
            throw new BussinessException(ResultCode.NO_lOGIN);
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //用户不为空，比对密码 传进来的处理后和数据库拿出来的对比
        if(!passwordEncoder.matches(user.getPassword(),user1.getPassword())){
//        if(!user1.getPassword().equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

//往map里添加   token & 用户信息(包括复制vo)
        Map<String,Object> map = new HashMap<>();
        String token = UUID.randomUUID().toString().replaceAll("-","");
//        jwt + redis + token  通过token，使用jwt，生成一个不会重复的jwtToken
//        jwtToken要保存到redis里面
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("uuid",token);
        claims.put("username",user1.getUserName());
//        jwttoken里面不存放过期时间，原因是
        String jwtToken = JwtUtils.createToken(claims);


        LoginUser loginUser = new LoginUser();
//        拷贝user的属性到loginuser
        BeanUtils.copyProperties(user1,loginUser);
//        System.out.println(loginUser);
//        设置登陆时间
        long curTime = System.currentTimeMillis();
        loginUser.setLoginTime(curTime);
//        设置过期时间
//        long类型是ms
        loginUser.setExprieTime(curTime+30*60*1000);
        List<String> perms = menuMapper.getPermsByRoleId(user1.getUserType());
        loginUser.setPerms(perms);
//把当前登录用户 存入redis 中
//第一个参数 key，第二个参数value 第三个参数 存活时长 （Long类型）， 第四个参数 （存活时长的）单位
        stringRedisTemplate.opsForValue().set("LOGIN:USER:"+token, JSONUtil.toJsonStr(loginUser),3l, TimeUnit.MINUTES);

        map.put("token",jwtToken);
        map.put("user",loginUser);
        log.info("============"+jwtToken);
        return map;

    }


    /**
     * 根据条件查询
     * @param user
     * @return
     */
    @Override
     public List<User> getUsersByCondition(User user) {
         List<User> users = userMapper.getUsersByCondition(user);
         return users;
    }

    @Override
    public int changeUserActive(User user) {
        return userMapper.changeUserActive(user);
    }

    @Override
    public int addUser(User user) {
        String phoneNumber = user.getPhoneNumber();
        String DefaultPassword = phoneNumber.substring(phoneNumber.length() - 6);
        //加密
        String encode = passwordEncoder.encode(DefaultPassword);
        user.setPassword(encode);
        return userMapper.addUser(user);
    }

    @Override
    public int editUser(User user) {
//        String encode = passwordEncoder.encode(user.getPassword());
//        user.setPassword(encode);
        user.setRoleId(user.getUserType());
        return userMapper.editUser(user);
    }

    @Override
    public int deleteUserByIds(String[] delList) {
        int i = lawyerMapper.deleteUserByIds(delList);
        return userMapper.deleteByIds(delList);
    }

    @Override
    public int reSetPassword(Integer userId) {
        return userMapper.reSetPassword(userId);

    }

    @Override
    public User getUserByName(String userName) {
        return userMapper.getUserByName(userName);
    }

    @Override
    public int editUserinfo(User user) {
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
//        user.setRoleId(user.getUserType());
        return userMapper.editUser(user);
    }
}
